package com.eystar.pdc.util;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.eystar.pdc.model.User;

import cn.hutool.core.util.StrUtil;


public class PdcHelper {

	/**
	 * 是否有用户登录
	 * @param request
	 * @return
	 */
	public static boolean hasLogin(HttpServletRequest request){
		return getCurrentUser(request) == null;
	}
	
	/**
	 * 获取当前用户
	 * @param request
	 * @return
	 */
	public static User getCurrentUser(HttpServletRequest request){
		HttpSession session = request.getSession();
		return (User) session.getAttribute(LoginUtil.SESSION_CURRENT_USER);
	}
	
	/**
	 * 获取用户等级，0-集团用户和超级管理员用户。1-省用户，2-地市用户，3-区用户
	 * @param request
	 * @return
	 */
	public static int getUserLevel(HttpServletRequest request){
		if (isSuper(request)) {
			return 0;
		}
		User user = getCurrentUser(request);
		if (user == null) { // 如果会话中获取不到用户，默认是最小权限
			return 3;
		}
		Long regionCode = user.getLong("region_code");
		if (regionCode == 100000) { // 集团
			return 0;
		}else if(regionCode % 10000 == 0){
			return 1;
		}else if(regionCode % 100 == 0){
			return 2;
		}else {
			return 3;
		}
	}
	
	/**
	 * 获取当前用户名称
	 * @param request
	 * @return
	 */
	public static String getCurrentUserName(HttpServletRequest request){
		User user = getCurrentUser(request);
		return user == null ? "" : user.getStr("user_name");
	}
	
	/**
	 * 是否是超级管理员
	 * @param request
	 * @return
	 */
	public static boolean isSuper(HttpServletRequest request){
		User user = getCurrentUser(request);
		if (user == null) {
			return false;
		}
		Integer level = user.getInt("role_flag");
		if(level == null || level != LoginUtil.ROLE_SUPER){
			return false;
		}
		return true;
	}
	
	public static boolean isAdmin(HttpServletRequest request){
		User user = getCurrentUser(request);
		if (user == null) {
			return false;
		}
		Integer level = user.getInt("role_flag");
		if(level == null || level != LoginUtil.ROLE_SUPER){
			return false;
		}
		return true;
	}
	
	/**
	 * 判断当前登录用户是否有权限关键字
	 * @param request
	 * @param authority
	 * @return
	 */
	public static boolean hasAuth(HttpServletRequest request,String authority){
		User user = getCurrentUser(request);
		if (user == null) {
			return false;
		}
		Set<String> authorities = user.get("authorities");
		return StrUtil.isNotBlank(authority) && authorities.contains(authority);
	}
}
